<?php 
namespace Modules\Category\Traits;

trait Categoryable
{
    public function getType()
    {
        // 获取在关联表中type字段的使用值，如果entity中没有定义，则使用表名中前30位字符

        return $this->resourceType ?: substr(str_singular($this->table), 0, 30);
    }

    public function scopeCategory($query, $categoryId)
    {
        return $query->whereHas('categories', function ($q) use ($categoryId) {
            return $q->where('id', $categoryId);
        });
    }

    public function scopeCategories($query, $categoryIds)
    {
        return $query->whereHas('categories', function ($q) use ($categoryIds) {
            return $q->whereIn('id', $categoryIds);
        });
    }

    public function categories()
    {
        $type = $this->getType();

        return $this->belongsToMany('\Modules\Category\Entities\Category', 'category_relations', 'target_id', 'category_id')->wherePivot('type', $type);
    }

    public function syncCategories($ids)
    {
        $type = $this->getType();

        $newIds = [];
        foreach ($ids as $id) {
            $newIds[$id] = [
                'type' => $type
            ];
        }
        
        \Log::error($newIds);

        $this->categories()->sync($newIds);
    }

    public function updateCategoryRelation()
    {
        $ids = $this->category_ids ?: [];
        $this->syncCategories($ids);
    }
}
?>